﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Zeta.Common;
/* Thanks to Highvoltz for pretty much all the code in this class.
 * I copy/pasted his whole updater class and changed only minor things
 * for my own liking.
 */
namespace SarkothFarmer.Helpers
{
    public static class Updater
    {
        private const string SfSvnUrl = "http://inrego-db-stuff.googlecode.com/svn/trunk/Plugins/SarkothFarmer/";
        private const string SfChangeLogUrl = "http://code.google.com/p/inrego-db-stuff/source/detail?r=";
        private static readonly Regex _linkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>",
                                                               RegexOptions.CultureInvariant);

        private static readonly Regex _changelogPattern =
            new Regex(
                "<h4 style=\"margin-top:0\">Log message</h4>\r?\n?<pre class=\"wrap\" style=\"margin-left:1em\">(?<log>.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?.+\r?\n?)</pre>",
                RegexOptions.CultureInvariant);

        public static void CheckForUpdate()
        {
            try
            {
                Logger.Write("Checking for new version");
                int remoteRev = GetRevision();
                if (Main.settingsWrapper.CurrentRev < remoteRev)
                {
                    StringBuilder windowText = new StringBuilder();
                    windowText.Append("A new version of SarkothFarmer has been found, do you want to update to r");
                    windowText.Append(remoteRev);
                    windowText.Append("?\n\nChanges since last update (showing 5 updates max):\n");
                    windowText.Append(GetChangeLogs(Main.settingsWrapper.CurrentRev, remoteRev));
                    switch (MessageBox.Show(windowText.ToString(),
                    "SarkothFarmer Update",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question))
                    {
                        case DialogResult.Yes:
                            Logger.Write("Downloading update.");
                            DownloadFilesFromSvn(new WebClient(), SfSvnUrl);
                            Logger.Write("Download complete.");
                            Main.settingsWrapper.CurrentRev = remoteRev;
                            Main.settingsWrapper.SaveGlobalSettings();
                            Logger.Write("A new version was installed. Please restart DemonBuddy");
                            break;

                        case DialogResult.No:
                            Logger.Write("User declined update. Will prompt again on next new update.");
                            Main.settingsWrapper.CurrentRev = remoteRev;
                            Main.settingsWrapper.SaveGlobalSettings();
                            break;
                    }
                }
                else
                {
                    Logger.Write("No updates found.");
                }
            }
            catch (Exception ex)
            {
                Logger.Write(ex.ToString());
            }
        }

        private static int GetRevision()
        {
            var client = new WebClient();
            string html = client.DownloadString(SfSvnUrl);
            var pattern = new Regex(@" - Revision (?<rev>\d+):", RegexOptions.CultureInvariant);
            Match match = pattern.Match(html);
            if (match.Success && match.Groups["rev"].Success)
                return int.Parse(match.Groups["rev"].Value);
            throw new Exception("Unable to retreive revision");
        }

        private static void DownloadFilesFromSvn(WebClient client, string url)
        {
            string html = client.DownloadString(url);
            MatchCollection results = _linkPattern.Matches(html);

            IEnumerable<Match> matches = from match in results.OfType<Match>()
                                         where match.Success && match.Groups["ln"].Success
                                         select match;
            foreach (Match match in matches)
            {
                string file = RemoveXmlEscapes(match.Groups["ln"].Value);
                string newUrl = url + file;
                if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                {
                    DownloadFilesFromSvn(client, newUrl);
                }
                else // its a file.
                {
                    string filePath, dirPath;
                    if (url.Length > SfSvnUrl.Length)
                    {
                        string relativePath = url.Substring(SfSvnUrl.Length);
                        dirPath = Path.Combine(Environment.CurrentDirectory, "Plugins", "SarkothFarmer", relativePath);
                        filePath = Path.Combine(dirPath, file);
                    }
                    else
                    {
                        dirPath = Environment.CurrentDirectory;
                        filePath = Path.Combine(Environment.CurrentDirectory, "Plugins", "SarkothFarmer", file);
                    }
                    Logger.WriteVerbose("Downloading {0}", file);
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);
                    client.DownloadFile(newUrl, filePath);
                }
            }
        }

        private static string RemoveXmlEscapes(string xml)
        {
            return
                xml.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace(
                    "&apos;", "'");
        }

        private static string GetChangeLog(int revision)
        {
            var client = new WebClient();
            string html = client.DownloadString(SfChangeLogUrl + revision);
            Match match = _changelogPattern.Match(html);
            if (match.Success && match.Groups["log"].Success)
                return RemoveXmlEscapes(match.Groups["log"].Value);
            return null;
        }
        private static string GetChangeLogs(int currentRevision, int newRevision)
        {
            StringBuilder changeLog = new StringBuilder();
            for (int i=newRevision; i > currentRevision && i > newRevision - 5; i--)
            {
                changeLog.Append("Revision " + i);
                string log = GetChangeLog(i).Replace("\n", " ");
                if (log.StartsWith("* "))
                {
                    changeLog.Append(log.Replace("* ", "\n * "));
                }
                else
                {
                    changeLog.Append("\n * " + log);
                }
                changeLog.Append("\n\n");
            }
            return changeLog.ToString();
        }
    }
}

// QmUgY29vbCBhbmQganVzdCBidXkgdGhlIGJvdA==
//!CompilerOption:AddRef:\u0052\u0065\u006D\u006F\u0074\u0069\u006E\u0067\u002E\u0064\u006C\u006C